package club.menglinking.wechat.util;

import club.menglinking.wechat.entity.TextTypeEntity;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName XmlUtil
 * @Author Administrator
 * @Date 2018/12/30 16:29
 * @Version 1.0
 * @Description
 **/
public class XmlUtil {
    private static XmlUtil xmlUtil=null;
    private XmlUtil(){}
    public static XmlUtil getXmlUtil(){
        if (xmlUtil == null){
            xmlUtil=new XmlUtil();
        }
        return xmlUtil;
    }
    public Map<String,String> xmlToMap(HttpServletRequest request){
        Map<String,String> map = new HashMap<String,String>();
        SAXReader reader = new SAXReader();
        InputStream in = null;
        try {
            in = request.getInputStream();
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            List<Element> list = root.elements();
            for (Element element : list) {
                map.put(element.getName(), element.getText());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    public String ReturnMsg(TextTypeEntity entity){
        //构建xml文本
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("xml");
        Element toUserName = root.addElement("ToUserName");
        toUserName.setText(entity.getToUserName());
        Element fromUserName = root.addElement("FromUserName");
        fromUserName.setText(entity.getFromUserName());
        Element createTime = root.addElement("CreateTime");
        createTime.setText(entity.getCreatetime());
        Element msgType = root.addElement("MsgType");
        msgType.setText(entity.getMsgType());
        Element content = root.addElement("Content");
        content.setText(entity.getContent());
        return root.asXML();
    }
}
